package com.cms.server.controller;


import com.cms.server.mapper.ContractAttachmentMapper;
import com.cms.server.model.Contract_attachment;
import com.cms.server.tool.Global;
import com.cms.server.tool.Timestamp;
import com.cms.server.tool.sendMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Map;

@RestController
@RequestMapping("/File")
public class FileController {
    @Resource
    private ContractAttachmentMapper contractAttachmentMapper;

    @CrossOrigin
    @PostMapping("/upFile")
    public ResponseEntity<Map<String,Object>> saveFile(MultipartFile file, HttpServletRequest request) {
        if (file == null || file.isEmpty()) {
            return ResponseEntity.badRequest().body(sendMessage.createResponse(false, "No file uploaded"));
        }
        String headers = String.valueOf(request.getHeaderNames());
        String filePath = "D:/programing/IDEA/contract-management-system/data/";
        String fileName = file.getOriginalFilename();
        String fileType = file.getContentType();

        File tempFile = new File(filePath + File.separator + fileName);

        try {
            // 确保目录存在
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }

            // 保存文件
            InputStream inputStream = file.getInputStream();
            Files.copy(inputStream, tempFile.toPath());

            Contract_attachment contract_attachment = new Contract_attachment();
            contract_attachment.setUploadTime(Timestamp.now_time());
            contract_attachment.setDel(0);
            contract_attachment.setCon_id(Integer.parseInt(headers));
            // 设置文件信息
            contract_attachment.setPath(filePath);
            contract_attachment.setType(fileType);
            contract_attachment.setFileName(fileName);
            // 插入数据库
            contractAttachmentMapper.insert(contract_attachment);
            return ResponseEntity.ok(sendMessage.createResponse(true, filePath + File.separator + fileName));

        } catch (IOException e) {
            // 日志记录异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(sendMessage.createResponse(false, "Error saving file:" + e.getMessage()+ " " + filePath ));
        }

    }


}
